(function($){  
	$.fn.textGoogleTranslate = function(options) {   
		var defaults = {
			targetLanguage: '',
			translatedPrefix: '',
			translatedPostfix: '',
			fadeOutDelay: 500,
			autoClose: true
		};
		
		var options = $.extend(defaults, options);
		
		if(options.targetLanguage == ''){
			alert('Target Language Setting is required!');
			return;
		}
		
		var selectText = '';
		var container = $(this);
		
		container.mouseup(function(event){
			selectedText = getSelText();

			if($('.translatedPanel').size() != 0){
				$('.translatedPanel').delay(options.fadeOutDelay).remove();
			}
			
			var translatePanel = $("<div class='translatedPanel' style='position: absolute; display: none;'>&nbsp;</div>");
  			translatePanel.appendTo(container);
  			
			if(selectedText != '') {
				google.language.detect(selectedText, function(result){
				  	if(!result.error && result.language){
				    	google.language.translate(String(selectedText), result.language, options.targetLanguage, function(result){								
			      			if(result.translation) {
			      				
			      				translatePanel.html(options.translatedPrefix + result.translation + options.translatedPostfix);
			      				
			      				var offsetTop = event.pageY-translatePanel.height()-8+$(document).scrollTop();
			      				var offsetLeft = event.pageX + $(document).scrollLeft();
				      			translatePanel.offset({top: offsetTop, left: offsetLeft});
				      			
				      			translatePanel.show();
			      			}
				    	});
			    	}
				});
			}
		});
		
		if(options.autoClose){
			container.mousemove(function(event){
				if($('.translatedPanel').size() != 0){
					$('.translatedPanel').delay(options.fadeOutDelay).fadeOut('slow');
				}
			});
		}
		
		
		function getSelText(){
			var txt = '';
		    if (window.getSelection){
		       txt = window.getSelection();
		    }else if (document.getSelection){
		       txt = document.getSelection();
		    }else if (document.selection){
		       txt = document.selection.createRange().text;
			}else 
				 return;
			return txt;	
		}
	};  
})(jQuery); 